#include "event_demo.h"


UINT32 tid_event;
UINT32 tid_sunblind;

#define EVT_WORK 	0x01
#define EVT_REST 	0x02
#define EVT_EARLY 	0x04
#define EVT_LATER 	0x08
#define EVT_NIGHT 	0x10
UINT32 evt_array[5]={EVT_WORK, EVT_REST, EVT_EARLY, EVT_LATER, EVT_NIGHT};
char log[5][15] = {"工作日", "休息日", "早7点", "上午10点", "晚8点"};

EVENT_CB_S event;

static void task_event(VOID){
	UINT32 i;

    while (1){
		// 随机种子，保证每次产生的随机数不一样
		srand(time(NULL));
		// 产生[0,4]的随机数
		i = rand()%5;
		printf("event %s happened\n", log[i]);
		// 将事件写入事件控制块
		LOS_EventWrite(&event, evt_array[i]);
        LOS_TaskDelay(10000);
    }
    return;
}

static void task_sunblind(VOID)
{
    UINT32 ret;
    while (1){
        //printf("read event\n");
        /* 读取事件并清除，使用逻辑与*/
        ret = LOS_EventRead(&event, EVT_WORK|EVT_EARLY, \
							LOS_WAITMODE_AND|LOS_WAITMODE_CLR, 0);
        if(ret == (EVT_WORK | EVT_EARLY)){ 
			printf("open sunblind at 7:00.am\n"); 
		}    
		/* 读取事件并清除，使用逻辑或*/
		ret = LOS_EventRead(&event, EVT_REST|EVT_LATER, \
							LOS_WAITMODE_OR|LOS_WAITMODE_CLR, 0);
        if(ret==EVT_REST || ret==EVT_LATER){ 
			printf("open sunblind at 10:00.am\n"); 
		}   
		/* 读取事件并清除，使用逻辑或*/
		ret = LOS_EventRead(&event, EVT_NIGHT, \
							LOS_WAITMODE_OR|LOS_WAITMODE_CLR, 0);
        if(ret == EVT_NIGHT){ 
			printf("colse sunblind at 8:00.pm\n"); 
		}   	
		LOS_TaskDelay(5);
    }
    return;
}

static UINT32 my_task(UINT32 tid, char *name, UINT16 pri, UINT32 stack_size, TSK_ENTRY_FUNC func) {
    UINT32 ret;
    TSK_INIT_PARAM_S param=={0};

    // 锁住任务调度，防止高优先级任务调度
    LOS_TaskLock();
    // 任务名字
    param.pcName = name;
    // 任务入口地址
    param.pfnTaskEntry = func;
    // 任务优先级
    param.usTaskPrio = pri;
    // 任务栈
    param.uwStackSize = stack_size;
    // 调用系统函数，创建任务。成功之后任务处于就绪状态
    ret = LOS_TaskCreate(&tid, &param);
	// 创建任务失败
    if (ret != LOS_OK) { printf("create task failed, errno = %x\n", ret); }
    //解锁任务调度
    LOS_TaskUnlock();

    return ret;
}

UINT32 event_entry(){
	UINT32 ret;

	// 初始化事件控制块
   	ret = LOS_EventInit(&event);
    if(ret != LOS_OK){ printf("init event failed\n"); return -1; }

	// 创建任务
	ret = my_task(&tid_sunblind, "task-sunblind", 9, 0x2000, task_sunblind);
	if(ret != LOS_OK){ printf("create task_sunblind failed\n"); return -1; }
	ret = my_task(&tid_event, "task-event", 10, 0x2000, task_event);
	if(ret != LOS_OK){ printf("create task_event failed\n"); return -1; }

	return ret;
}
SYS_RUN(event_entry);